/**
 * 
 */
package kg.tool.network;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Map;
import java.util.Map.Entry;

/**
 * 網路相關函數，可以利用來取得網頁
 * @author kahiro
 */
public class NetworkUtil {
	private static NetworkUtil instance;
	
	private NetworkUtil(){}
	
	public static NetworkUtil getInstance(){
		if(instance == null){
			instance = new NetworkUtil();
		}
		return instance;
	}
	
	/**
	 * get page source code from url
	 * @param sURL url string,ex:http://www.google.com
	 * @param code encode, ex:big5、utf-8
	 * @return
	 */
	public String getPage(String sURL, String code){
		return getPage(sURL, code, null);
	}
	
	/**
	 * get page source code from url
	 * @param sURL url string,ex:http://www.google.com
	 * @param code encode, ex:big5、utf-8
	 * @param rpMap other properties
	 * @return
	 */
	public String getPage(String sURL, String code, Map<String, String> rpMap){
		try {
			//使用properties需要加入以下的code
//			Properties properties = System.getProperties();
//			properties.setProperty("http.proxyHost", "10.160.128.16");
//			properties.setProperty("http.proxyPort", "8080");
			System.out.println("目標==>" + sURL + "\t編碼==>" + code);
			
			URL url = new URL(sURL);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//			HttpURLConnection.setFollowRedirects(true);
			conn.setRequestMethod("GET");
			if(rpMap != null){
				for(Entry<String, String> entry : rpMap.entrySet()){
					System.out.println("使用參數==>" + entry.getKey() + ":" + entry.getValue());
					conn.setRequestProperty(entry.getKey(), entry.getValue());
				}
			}
//			conn.setRequestProperty("User-Agent","Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit/537.20 (KHTML, like Gecko) Chrome/25.0.1337.0 Safari/537.20");
			//Referer為判斷是否從首頁進入
//			conn.setRequestProperty("Referer", "http://www.ytower.com.tw/recipe/recipe.asp");
			BufferedInputStream is = new BufferedInputStream(conn.getInputStream());
			ByteArrayOutputStream out = new ByteArrayOutputStream();
			byte[] b = new byte[1024];
			int len = 0;
			while((len = is.read(b)) > 0){
				out.write(b, 0, len);
			}
			is.close();
			String temp = new String(out.toByteArray(), code); 
			out.close();
//			System.out.println("輸出:" + temp);
			return temp;
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
}
